package com.oss.controller.corn;

import com.oss.dto.oss.importLog.DownloadDto;
import com.oss.entity.oss.Student;
import com.oss.service.oss.ImportLogService;
import com.oss.service.oss.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengqiang
 * 定时执行
 * corn 结构 秒 分 时 日 月 年
 */
@Slf4j
@EnableScheduling
@Component
@EnableAsync
public class TimedTask {
    @Autowired
    StudentService studentService;
    @Autowired
    ImportLogService importLogService;

    /**
     * 每天晚上7点自动下载
     * 异步执行
     * @throws Exception
     */
    @Async
    @Scheduled(cron = "00 00 19 * * ?")
    public void autoDownloadFile() throws Exception {
        List<Student> list = studentService.getAll();
        // 去掉账号和密码为空的学员信息
        list = list.stream().filter(item-> StringUtils.isNotBlank(item.getAccount()) && StringUtils.isNotBlank(item.getPassword())).collect(Collectors.toList());
        for (Student student : list) {
            DownloadDto dto = new DownloadDto();
            dto.setStudentID(student.getId());
            LocalDate now = LocalDate.now();
            dto.setTradeDate(now);
            // 当前日期是否为周六或周日 , 如果是 , 不需要下载
            boolean flag = now.getDayOfWeek() == DayOfWeek.SATURDAY || now.getDayOfWeek() == DayOfWeek.SUNDAY;
            if (flag) {
                log.info(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" , 当前日期是周六/周日不下载");
                continue;
            } else {
                try {
                    importLogService.download(dto);
                } catch (Exception e) {
                    log.error("定时任务下载异常 , 学员ID="+student.getId() + ";异常信息=" +e.getMessage());
                }
            }
        }
    }
}
